package com.xujie.sportsmeeting.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xujie.sportsmeeting.common.result.Result;
import com.xujie.sportsmeeting.dto.EventRegistrationDTO;
import com.xujie.sportsmeeting.dto.RegistrationAuditDTO;
import com.xujie.sportsmeeting.entity.Athlete;
import com.xujie.sportsmeeting.entity.CompetitionEvent;
import com.xujie.sportsmeeting.entity.EventRegistration;
import com.xujie.sportsmeeting.entity.SysUser;
import com.xujie.sportsmeeting.service.AthleteService;
import com.xujie.sportsmeeting.service.CompetitionEventService;
import com.xujie.sportsmeeting.service.EventRegistrationService;
import com.xujie.sportsmeeting.service.SysUserService;
import com.xujie.sportsmeeting.vo.EventRegistrationVO;
import com.xujie.sportsmeeting.vo.RegistrationAuditVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

/**
 * 项目报名管理控制器
 */
@Tag(name = "项目报名管理", description = "项目报名和审核接口")
@RestController
@RequestMapping("/registrations")
@RequiredArgsConstructor
public class EventRegistrationController {

    private final EventRegistrationService eventRegistrationService;
    private final CompetitionEventService competitionEventService;
    private final AthleteService athleteService;
    private final SysUserService sysUserService;

    @Operation(summary = "分页查询报名记录")
    @GetMapping
    @PreAuthorize("hasAnyAuthority('system:user', 'judge', 'athlete')")
    public Result<Page<RegistrationAuditVO>> pageRegistrations(
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Long eventId,
            @RequestParam(required = false) Integer auditStatus) {
        
        Page<EventRegistration> page = new Page<>(current, size);
        LambdaQueryWrapper<EventRegistration> wrapper = new LambdaQueryWrapper<>();
        
        // 获取当前用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        SysUser currentUser = sysUserService.findByUsername(username);
        List<String> roles = sysUserService.findRolesByUserId(currentUser.getId());
        
        // 如果是运动员角色，只能查看自己的报名记录
        if (roles.contains("ATHLETE")) {
            Athlete athlete = athleteService.findByUserId(currentUser.getId());
            if (athlete != null) {
                wrapper.eq(EventRegistration::getAthleteId, athlete.getId());
            } else {
                // 如果找不到对应的运动员记录，返回空结果
                return Result.success(new Page<>(current, size, 0));
            }
        }
        
        // 条件查询
        if (eventId != null) {
            wrapper.eq(EventRegistration::getEventId, eventId);
        }
        if (auditStatus != null) {
            wrapper.eq(EventRegistration::getAuditStatus, auditStatus);
        }
        
        wrapper.eq(EventRegistration::getStatus, 1)
               .orderByDesc(EventRegistration::getCreateTime);
        
        Page<EventRegistration> result = eventRegistrationService.page(page, wrapper);
        
        // 转换为VO
        Page<RegistrationAuditVO> voPage = new Page<>(result.getCurrent(), result.getSize(), result.getTotal());
        voPage.setRecords(result.getRecords().stream().map(registration -> {
            RegistrationAuditVO vo = new RegistrationAuditVO();
            BeanUtils.copyProperties(registration, vo);
            
            // 查询项目信息
            CompetitionEvent event = competitionEventService.getById(registration.getEventId());
            if (event != null) {
                vo.setEventName(event.getEventName());
                vo.setEventCode(event.getEventCode());
                vo.setEventType(event.getEventType());
                vo.setGenderLimit(event.getGenderLimit());
            }
            
            // 查询运动员信息
            Athlete athlete = athleteService.getById(registration.getAthleteId());
            if (athlete != null) {
                vo.setAthleteName(athlete.getRealName());
                vo.setStudentNumber(athlete.getStudentNumber());
                vo.setAthleteGender(athlete.getGender());
                vo.setDepartment(athlete.getDepartment());
                vo.setClassName(athlete.getClassName());
                vo.setPhone(athlete.getPhone());
            }
            
            // 查询审核人信息
            if (registration.getAuditUserId() != null) {
                SysUser auditUser = sysUserService.getById(registration.getAuditUserId());
                if (auditUser != null) {
                    vo.setAuditUserName(auditUser.getRealName());
                }
            }
            
            // 关键字过滤（在查询结果中过滤）
            if (StringUtils.hasText(keyword)) {
                String searchText = (vo.getAthleteName() + vo.getStudentNumber() + 
                                   vo.getEventName() + vo.getRegistrationNumber()).toLowerCase();
                if (!searchText.contains(keyword.toLowerCase())) {
                    return null;
                }
            }
            
            return vo;
        }).filter(vo -> vo != null).toList());
        
        return Result.success(voPage);
    }

    @Operation(summary = "运动员报名项目")
    @PostMapping
    @PreAuthorize("hasAnyAuthority('athlete', 'system:user')")
    public Result<Void> registerEvent(@Valid @RequestBody EventRegistrationDTO registrationDTO) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        SysUser currentUser = sysUserService.findByUsername(username);
        
        // 如果是运动员角色，只能为自己报名
        List<String> roles = sysUserService.findRolesByUserId(currentUser.getId());
        if (roles.contains("ATHLETE")) {
            Athlete athlete = athleteService.findByUserId(currentUser.getId());
            if (athlete == null || !athlete.getId().equals(registrationDTO.getAthleteId())) {
                return Result.error("只能为自己报名");
            }
        }
        
        eventRegistrationService.registerEvent(
            registrationDTO.getEventId(), 
            registrationDTO.getAthleteId(), 
            registrationDTO.getRemarks()
        );
        
        return Result.success("报名成功，等待审核");
    }

    @Operation(summary = "审核报名")
    @PostMapping("/audit")
    @PreAuthorize("hasAuthority('system:user')")
    public Result<Void> auditRegistration(@Valid @RequestBody RegistrationAuditDTO auditDTO) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        SysUser currentUser = sysUserService.findByUsername(username);
        
        eventRegistrationService.auditRegistration(
            auditDTO.getRegistrationId(),
            auditDTO.getAuditStatus(),
            auditDTO.getAuditRemark(),
            currentUser.getId()
        );
        
        String statusText = auditDTO.getAuditStatus() == 1 ? "通过" : "拒绝";
        return Result.success("审核" + statusText + "成功");
    }

    @Operation(summary = "批量审核报名")
    @PostMapping("/audit/batch")
    @PreAuthorize("hasAuthority('system:user')")
    public Result<Void> batchAuditRegistrations(@RequestBody List<RegistrationAuditDTO> auditList) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        SysUser currentUser = sysUserService.findByUsername(username);
        
        for (RegistrationAuditDTO auditDTO : auditList) {
            eventRegistrationService.auditRegistration(
                auditDTO.getRegistrationId(),
                auditDTO.getAuditStatus(),
                auditDTO.getAuditRemark(),
                currentUser.getId()
            );
        }
        
        return Result.success("批量审核完成");
    }

    @Operation(summary = "取消报名")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAnyAuthority('athlete', 'system:user')")
    public Result<Void> cancelRegistration(@PathVariable Long id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        SysUser currentUser = sysUserService.findByUsername(username);
        
        // 如果是运动员，只能取消自己的报名
        List<String> roles = sysUserService.findRolesByUserId(currentUser.getId());
        if (roles.contains("ATHLETE")) {
            Athlete athlete = athleteService.findByUserId(currentUser.getId());
            if (athlete != null) {
                eventRegistrationService.cancelRegistration(id, athlete.getId());
            }
        } else {
            // 管理员可以取消任何报名
            EventRegistration registration = eventRegistrationService.getById(id);
            if (registration != null) {
                eventRegistrationService.cancelRegistration(id, registration.getAthleteId());
            }
        }
        
        return Result.success("取消报名成功");
    }

    @Operation(summary = "根据项目查询报名列表")
    @GetMapping("/event/{eventId}")
    @PreAuthorize("hasAnyAuthority('system:user', 'judge')")
    public Result<List<RegistrationAuditVO>> getEventRegistrations(@PathVariable Long eventId) {
        List<EventRegistration> registrations = eventRegistrationService.getEventRegistrations(eventId);
        
        List<RegistrationAuditVO> voList = registrations.stream().map(registration -> {
            RegistrationAuditVO vo = new RegistrationAuditVO();
            BeanUtils.copyProperties(registration, vo);
            
            // 查询项目信息
            CompetitionEvent event = competitionEventService.getById(registration.getEventId());
            if (event != null) {
                vo.setEventName(event.getEventName());
                vo.setEventCode(event.getEventCode());
                vo.setEventType(event.getEventType());
                vo.setGenderLimit(event.getGenderLimit());
            }
            
            // 查询运动员信息
            Athlete athlete = athleteService.getById(registration.getAthleteId());
            if (athlete != null) {
                vo.setAthleteName(athlete.getRealName());
                vo.setStudentNumber(athlete.getStudentNumber());
                vo.setAthleteGender(athlete.getGender());
                vo.setDepartment(athlete.getDepartment());
                vo.setClassName(athlete.getClassName());
                vo.setPhone(athlete.getPhone());
            }
            
            // 查询审核人信息
            if (registration.getAuditUserId() != null) {
                SysUser auditUser = sysUserService.getById(registration.getAuditUserId());
                if (auditUser != null) {
                    vo.setAuditUserName(auditUser.getRealName());
                }
            }
            
            return vo;
        }).toList();
        
        return Result.success(voList);
    }

    @Operation(summary = "根据运动员查询报名列表")
    @GetMapping("/athlete/{athleteId}")
    @PreAuthorize("hasAnyAuthority('athlete', 'system:user')")
    public Result<List<EventRegistrationVO>> getAthleteRegistrations(@PathVariable Long athleteId) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        SysUser currentUser = sysUserService.findByUsername(username);
        
        // 如果是运动员，只能查看自己的报名
        List<String> roles = sysUserService.findRolesByUserId(currentUser.getId());
        if (roles.contains("ATHLETE")) {
            Athlete athlete = athleteService.findByUserId(currentUser.getId());
            if (athlete == null || !athlete.getId().equals(athleteId)) {
                return Result.error("只能查看自己的报名记录");
            }
        }
        
        List<EventRegistration> registrations = eventRegistrationService.getAthleteRegistrations(athleteId);
        
        List<EventRegistrationVO> voList = registrations.stream().map(registration -> {
            EventRegistrationVO vo = new EventRegistrationVO();
            BeanUtils.copyProperties(registration, vo);
            
            // 查询项目信息
            CompetitionEvent event = competitionEventService.getById(registration.getEventId());
            if (event != null) {
                vo.setEventName(event.getEventName());
            }
            
            // 查询运动员信息
            Athlete athlete = athleteService.getById(registration.getAthleteId());
            if (athlete != null) {
                vo.setAthleteName(athlete.getRealName());
                vo.setStudentNumber(athlete.getStudentNumber());
            }
            
            // 查询审核人信息
            if (registration.getAuditUserId() != null) {
                SysUser auditUser = sysUserService.getById(registration.getAuditUserId());
                if (auditUser != null) {
                    vo.setAuditUserName(auditUser.getRealName());
                }
            }
            
            return vo;
        }).toList();
        
        return Result.success(voList);
    }

    @Operation(summary = "获取待审核报名统计")
    @GetMapping("/audit/pending")
    @PreAuthorize("hasAuthority('system:user')")
    public Result<Long> getPendingAuditCount() {
        LambdaQueryWrapper<EventRegistration> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EventRegistration::getAuditStatus, 0)
               .eq(EventRegistration::getStatus, 1);
        long count = eventRegistrationService.count(wrapper);
        return Result.success(count);
    }
}
